<template>
  <div class="app-container cliptask">
    <!-- 截图临时容器 -->
    <div id="mainContainer" class="up s-border">
      <live-video-area-view
        v-if="video && video.sourceUrl"
        id="mainPlayer"
        ref="mainPlayer"
        :url="video.sourceUrl"
        :muted="true"
        style="width: 300px; height: 200px;display:none;"/>
    </div>

    <!-- 查询和其他操作 -->

    <div class="filter-container">
      <el-input v-model="listQuery.title" clearable class="filter-item" style="width: 200px;" placeholder="请输入名称"/>
      <el-date-picker
        v-model="listQuery.beginTime"
        class="filter-item"
        format="yyyy-MM-dd HH:mm:ss"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetime"
        style=""
        placeholder="选择开始日期"/>
      <el-date-picker
        v-model="listQuery.endTime"
        class="filter-item"
        format="yyyy-MM-dd HH:mm:ss"
        value-format="yyyy-MM-dd HH:mm:ss"
        type="datetime"
        style=""
        placeholder="选择结束日期"/>
      <div class="buttonGroup">
        <el-button class="filter_button" icon="el-icon-search" @click="handleFilter">查找</el-button>
        <el-button class="filter_button" type="primary" icon="el-icon-plus" @click="handleCreate">添加</el-button>
      </div>
    </div>
    <!-- 查询结果 -->
    <MCTable :data-source="taskSource"/>
    <pagination :total="total" :page.sync="page" :limit.sync="listQuery.limit" @pagination="sizeChange" />
    <!-- 新建剪辑任务弹窗 -->
    <el-dialog v-if="dialogFormVisible" :visible.sync="dialogFormVisible" title="添加剪辑素材" style="width: 100%;" close>
      <el-form ref="dataForm" :model="dataForm" status-icon label-position="right" label-width="120px" style="width: 90%; margin-left:20px;">
        <el-form-item>
          <el-button type="primary" size="mini" @click="selectSource">素材库选择</el-button>
          <el-button type="primary" size="mini" @click="videotype=1,dataForm.sourceUrl=''">m3u8链接视频</el-button>
          <el-button type="primary" size="mini" @click="videotype=2,dataForm.sourceUrl=''">本地上传视频</el-button>
        </el-form-item>
        <el-form-item v-show="videotype==1" prop="sourceUrl" label="视频链接">
          <div>
            <el-input v-model="dataForm.sourceUrl" type="textarea" placeholder="输入m3u8链接地址" @blur="getm3u8"/>
          </div>
        </el-form-item>
        <el-form-item v-show="videotype==2" prop="sourceUrl" label="上传">
          <div>
            <file-uploader
              v-model="dataForm.sourceUrl"
              type="video"
              accept="video/mp4"
              @uploaded="onVideoLoaded"
              @beforeupload="beforeupload"
              @onRemove="onRemove"
              @onError="onError"/>
          </div>
        </el-form-item>
        <el-form-item v-show="Object.keys(videoinfo).length>0&&videotype==2">
          <div>
            <span>素材大小：{{ videoinfo.size }}</span>
            <span>素材时长：{{ videoinfo.time }}</span>
            <span>素材格式：{{ videoinfo.type }}</span>
          </div>
        </el-form-item>
        <el-form-item label="任务名称" prop="title">
          <el-input v-model="dataForm.title" type="textarea"/>
        </el-form-item>
        <el-form-item label="期数ID" prop="playId">
          <el-input v-model="dataForm.playId" type="textarea"/>
        </el-form-item>
        <el-form-item label="开启讯飞翻译" prop="enableConvertText">
          <el-switch
            v-model="dataForm.enableConvertText"
            :active-value="1"
            :inactive-value="0"
            active-color="#13ce66"
            inactive-color="#ff4949"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">关闭</el-button>
        <el-button v-if="dialogStatus=='create'" type="primary" @click="createData">确定</el-button>
        <el-button v-else type="primary" @click="updateData">确定</el-button>
      </div>
    </el-dialog>

    <!-- 媒资库选择弹窗 -->
    <el-dialog v-if="mediaSourceVisible" :visible.sync="mediaSourceVisible" title="选择资源" width="80%" close>
      <div class="filter-container">
        <el-input v-model="sourceQuery.text" clearable class="filter-item" style="width: 200px;" placeholder="请输入名称"/>
        <el-button class="filter-item" icon="el-icon-search" @click="searchsource_list">查找</el-button>
      </div>
      <div style="margin:10px 0;">
        <p>已选择:{{ showInfo }}</p>
      </div>
      <MCTable :data-source="mediaSource" @handleCurrentChange="handleSelectionChange"/>
      <pagination :total="total1" :page.sync="page1" :limit.sync="sourceQuery.limit" style="padding:0;" @pagination="sizeChange1" />
      <div slot="footer" class="dialog-footer" style="padding:0;margin:0;">
        <el-button @click="mediaSourceVisible = false">取消</el-button>
        <el-button type="primary" @click="sureSelect">确定选择</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>

import BackToTop from '../../../components/BackToTop'
import Pagination from '../../../components/Pagination'
import ObjectUtil from '../../../utils/object-util'
import { apiVideo as API } from '../../../api/clip/task'
import FileUploader from '../../../components/common/FileUploader'
// import RadioMeterialClipResult from './clipResult'
import Fn from '../../../utils/fn'
import { ClipVideoTypeContants, VideoStatusContants } from '../../../mixin/MixinContants'
import { apiMeterial } from '../../../api/mediaManage/index'
import { apiUpload } from '../../../api/upload'
import { FileUtil } from '../../../utils/file-util'
import LiveVideoAreaView from './views/LiveVideoAreaView'
import Common from '../../../utils/common'
import tagButton from '../../../components/common/tagButton'
import { taskColumn, mediaColumn } from './clipColumns/taskColumns'

export default {
  name: 'RadioMeterialTaskList',
  components: {
    // RadioMeterialClipResult,
    FileUploader,
    BackToTop,
    Pagination,
    LiveVideoAreaView,
    tagButton
  },
  mixins: [
    ClipVideoTypeContants.mixin,
    VideoStatusContants.mixin
  ],
  data() {
    return {
      // 任务列表数据源
      taskSource: {
        headerLines: 1,
        list: [],
        columns: taskColumn,
        operates: {
          fixed: 'right',
          width: '250',
          list: [
            { label: '剪辑', type: 'success', show: (row) => (true),
              method: (index, row) => {
                this.handleEdit(row)
              }
            },
            { label: '查看详情', type: 'info', show: (row) => (true),
              method: (index, row) => {
                this.todetail(row)
              }
            },
            { label: '重新下载任务', type: 'info', show: (row) => (true),
              method: (index, row) => {
                this.reDownloadTask(row)
              }
            },
            { label: '下载此任务所有剪辑', type: 'info', show: (row) => (true),
              method: (index, row) => {
                this.handleDownload(row)
              }
            },
            { label: '删除', type: 'info', show: (row) => (true),
              method: (index, row) => {
                this.handleDelete(row)
              }
            }
          ]
        }
      },
      // 弹窗列表数据源
      mediaSource: {
        list: [],
        columns: mediaColumn
      },
      video: { sourceUrl: '' },
      page: 1,
      page1: 1,
      total: 0,
      total1: 0,
      videotype: '',
      list: [],
      source_list: [],
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        id: undefined,
        tag: undefined,
        title: undefined,
        beginTime: undefined,
        endTime: undefined
      },
      sourceQuery: {
        page: 1,
        limit: 20,
        id: undefined,
        tag: undefined,
        text: undefined,
        type: 1,
        source: 1
        // auditStatus: 1,
        // inTrash: 0
      },
      dataForm: {
        enableConvertText: 1,
        playId: '',
        sourceUrl: '',
        title: '',
        // cateOneList: [],
        // cateTwoList: [],
        posterUrl: undefined,
        sourceType: undefined,
        meterialType: '1',
        sourceMeterialId: undefined
      },
      dialogFormVisible: false,
      mediaSourceVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      downloadLoading: false,
      // 视频信息
      videoinfo: {},
      showInfo: '',
      bizType: ''
    }
  },
  created() {
    this.Init()
  },
  methods: {
    onRemove() {
      this.videoinfo = {}
    },
    onError(file) {
      this.videoinfo = {}
    },
    // 重新下载剪辑任务
    reDownloadTask: Fn.Confirm(async function(task) {
      const [err, res] = await this.$await(API.reDownload({ id: task.id }))
      if (res) {
        this.toast.success('操作成功')
      }
    }, '是否重新下载？'),
    // 去剪辑详情
    todetail(row) {
      this.$router.push(`/clip/clipdetail?id=${row.id}&title=${row.title}`)
    },
    sureSelect() {
      this.video.sourceUrl = this.dataForm.sourceUrl
      this.mediaSourceVisible = false
    },
    // 上传
    uploaddata(data) {
      const form = new FormData()
      form.append('file', data)
      apiUpload.upload(form).then(res => {
        this.dataForm.posterUrl = res.data.datas.url
      }).catch()
    },
    // 从m3u8链接中获取封面
    getm3u8() {
      const index = this.dataForm.sourceUrl.lastIndexOf('.')
      const type = this.dataForm.sourceUrl.substring(index)
      const ism3u8 = type.trim(type)
      if (this.dataForm.sourceUrl == '') {
        return this.toast.fail('不能为空')
      } else if (ism3u8 != '.m3u8') {
        return this.toast.fail('不是m3u8的链接')
      }
      this.video.sourceUrl = this.dataForm.sourceUrl.trim()
    },
    // 单选
    handleSelectionChange(val) {
      console.log(val)
      this.dataForm.sourceUrl = val.url
      this.dataForm.sourceMeterialId = val.id
      this.showInfo = val.title
      this.dataForm.playId = val.playId || ''
      this.bizType = val.bizType
    },
    // 显示媒资库选择弹窗
    selectSource() {
      this.dataForm.sourceUrl = ''
      this.videotype = ''
      this.mediaSourceVisible = true
      this.$nextTick(() => {
        this.getsoureList()
      })
    },
    // 媒资库搜索
    searchsource_list() {
      this.page1 = 1
      this.getsoureList()
    },
    getNewStatus(status) {
      return (status + 1) % 2
    },
    Init() {
      this.getList()
    },
    // 列表搜索
    handleFilter() {
      this.page = 1
      this.getList()
    },
    sizeChange(val) {
      this.listQuery.limit = val.limit
      this.getList()
    },
    sizeChange1(val) {
      this.sourceQuery.limit = val.limit
      this.getsoureList()
    },
    // 页面列表的数据
    getList() {
      this.$set(this.taskSource, 'options', { loading: true })
      const { beginTime, endTime } = this.listQuery
      this.listQuery.beginTime = beginTime || undefined
      this.listQuery.endTime = endTime || undefined
      this.listQuery.page = this.page
      API.list({ ...this.listQuery }).then(res => {
        if (res.data.resp_code == 0) {
          this.taskSource.list = res.data.datas.list || []
          this.total = Number(res.data.datas.total)
        } else {
          this.toast.fail(res.data.resp_msg)
        }
      }).finally(() => {
        this.$set(this.taskSource, 'options', { loading: false })
      })
    },
    // 弹框媒资库列表数据
    getsoureList() {
      this.$set(this.mediaSource, 'options', { loading: true })
      this.sourceQuery.page = this.page1
      apiMeterial.listByTitle({ ...this.sourceQuery }).then(res => {
        if (res.data.resp_code == 0) {
          this.mediaSource.list = res.data.datas.list || []
          this.total1 = Number(res.data.datas.total)
        } else {
          this.toast.fail(res.data.resp_msg)
        }
      }).finally(() => {
        this.$set(this.mediaSource, 'options', { loading: false })
      })
    },
    beforeupload(data) {
      let c = ''
      const that = this
      const url = URL.createObjectURL(data)
      var audioElement = new Audio(url)
      audioElement.addEventListener('loadedmetadata', function() {
        const duration = parseInt((audioElement.duration)) // playTime就是当前视频长度
        const b = parseInt(duration) % 60
        if (duration > 60) {
          const a = parseInt(duration) / 60
          c = a + 'min' + b + 's'
        } else {
          c = b + 's'
        }
        that.$set(that.videoinfo, 'time', c)
        that.$set(that.videoinfo, 'size', (data.size / 1024 / 1024).toFixed(2) + 'MB')
        that.$set(that.videoinfo, 'type', data.type.split('/')[1])
      })
    },
    onVideoLoaded(data) {
      this.video.sourceUrl = data.url
    },
    resetForm() {
      this.dataForm = {
        playId: '',
        sourceUrl: '',
        title: '',
        // cateOneList: [],
        // cateTwoList: [],
        posterUrl: undefined,
        sourceType: undefined,
        meterialType: '1',
        enableConvertText: 1
      }
      this.videoinfo = {}
    },
    handleCreate() {
      this.videotype = ''
      this.resetForm()
      this.dialogStatus = 'create'
      this.mediaSourceVisible = false
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 创建任务
    createData() {
      if (this.dataForm.sourceUrl == '') {
        return this.toast.fail('请选择一个视频')
      }
      if (this.dataForm.title == '') {
        return this.toast.fail('请填写名称')
      }
      if (this.videotype) {
        this.$set(this.dataForm, 'sourceMeterialId', undefined)
        this.dataForm.sourceType = this.videotype == 1 ? 0 : 1
        if (!this.dataForm.playId) {
          return this.toast.fail('请输入期数id')
        }
      } else {
        this.dataForm.sourceType = 2
        if (this.bizType == 1) {
          if (!this.dataForm.playId) {
            return this.toast.fail('请输入期数id')
          }
        }
      }
      const loading = this.$loading({
        lock: true,
        text: '请稍等',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      // setTimeout(() => {
      this.$nextTick(() => {
        setTimeout(() => {
          const video = this.$refs.mainPlayer
          const poster = video.clipImage()
          this.dataForm.sourceUrl = this.dataForm.sourceUrl.trim()
          const create = () => {
            API.create(this.dataForm)
              .then(response => {
                if (response.data.resp_code == 0) {
                  this.getList()
                  this.dialogFormVisible = false
                  loading.close()
                  this.$notify.success({
                    title: '成功',
                    message: '创建成功'
                  })
                } else {
                  loading.close()
                  this.toast.fail(response.data.resp_msg)
                }
              })
              .catch(response => {
                loading.close()
                // alert(1)
                this.$notify.error({
                  title: '失败',
                  message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
                })
              })
          }
          // posterUrl 是否为url地址
          if (poster.match(/^data\:image/g)) {
            FileUtil.base64ToBolb(Common._randomString(12) + '.png', poster).then(res => {
              FileUtil.updateLoadFile(res).then(res => {
                const data = res.data.datas
                if (ObjectUtil.notNull(data) && ObjectUtil.notNull(data.url)) {
                  this.dataForm.posterUrl = data.url
                  create()
                }
              })
            })
          } else {
            create()
          }
        }, 1000)
      })
    },
    handleUpdate(row) {
      this.dataForm = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData() {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          API.update(this.dataForm)
            .then(() => {
              for (const v of this.list) {
                if (v.id === this.dataForm.id) {
                  const index = this.list.indexOf(v)
                  this.list.splice(index, 1, this.dataForm)
                  break
                }
              }
              this.dialogFormVisible = false
              this.$notify.success({
                title: '成功',
                message: '更新成功'
              })
            })
            .catch(response => {
              this.$notify.error({
                title: '失败',
                message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
              })
            })
        }
      })
    },
    handleDelete: Fn.Confirm(function(row) {
      API.delete({ id: row.id })
        .then(response => {
          if (response.data.resp_code === 0) {
            this.getList()
            this.$notify.success({
              title: '成功',
              message: '删除成功'
            })
          } else {
            this.toast.fail(response.data.resp_msg)
          }
          // const index = this.list.indexOf(row)
          // this.list.splice(index, 1)
        })
        .catch(response => {
          this.$notify.error({
            title: '失败',
            message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
          })
        })
    }),
    // 跳剪辑
    handleEdit(row) {
      this.$router.push({ name: 'RadioMeterialClipEdit', query: { id: row.id, title: row.title }})
      // if (row.downStatus == 1) {
      //   this.$router.push({ name: 'RadioMeterialClipEdit', query: { id: row.id, title: row.title }})
      // } else if (row.downStatus == 2) {
      //   this.toast.fail('任务下载失败，无法剪辑')
      // } else {
      //   this.toast.fail('后台正在处理，稍后再试')
      // }
    },
    handleDownload: Fn.Confirm(function(row) {
      const loading = this.$loading({
        lock: true,
        text: '下载中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      const finalName = (row.id || '0') + '_视频下载集合'
      API.cliplist_all({ taskId: row.id }).then(res => {
        const clipList = res.data.datas.list || []
        const pArr = []
        const fileDataList = []
        clipList.filter(clip => ObjectUtil.notEmpty(clip.meterialUrl)).forEach(clip => {
          fileDataList.push({ filename: clip.title + '.mp4', data: null })
          pArr.push(API.file(clip.meterialUrl)())
        })

        Promise.all(pArr).then(resList => {
          resList.forEach((data, index) => {
            console.log(data, index)
            fileDataList[index].data = data.data
          })
          FileUtil.fileBatchDownload(finalName, fileDataList).then(downRes => {
            this.$notify.success({
              title: '成功',
              message: '批量下载成功'
            })
          }).catch(response => {
            this.$notify.error({
              title: '失败',
              message: (response.data.resp_msg || {})['errmsg'] || '请联系系统管理员'
            })
          }).finally(() => {
            loading.close()
          })
        })
      })
    })
  }
}
</script>

<style lang='scss' scoped>
  .cliptask{
  }
</style>
